import { PageContainer } from '@ant-design/pro-layout';
import { FormInstance, Modal } from 'antd';
import { message } from 'antd';
import { Button, Divider } from 'antd';
import { useReducer, useRef, useState } from 'react';
import type { ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import styles from './index.less';
import type { RangePickerProps } from 'antd/lib/date-picker';
import { DatePicker } from 'antd';
import moment from 'moment';
import type { orderList } from './types';
import { couponTemplateItem, deleteTemplate, getOrderTable } from './service';
import { useModel } from 'umi';
import Detail from './mainContent/detail';
import type { ActionType } from '@ant-design/pro-table';
import { CloseCircleOutlined, ExclamationCircleFilled, PlusOutlined } from '@ant-design/icons';
import Add from './mainContent/add';
import { ModalForm, ProFormList, ProFormText } from '@ant-design/pro-form';

export default () => {
  const disabledDate: RangePickerProps['disabledDate'] = (current) => {
    // Can not select days before today and today
    return current && current > moment().endOf('day');
  };
  const actionRef = useRef<ActionType>();
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const tenantId = currUser?.tenantId;
  const formRef = useRef<FormInstance>();
  const [detailId, setDetailId] = useState<string>();
  const [pageName, setPageName] = useState<string>('优惠券列表');
  const [configCard, setConfigCard] = useState<boolean>(false);
  const [passVisible, setPassVisible] = useState<boolean>();

  const ElementComponent = {
    AddElement: (
      <Add
        close={() => {
          // eslint-disable-next-line @typescript-eslint/no-use-before-define
          AddClose();
        }}
      />
    ),
  };
  const [outVisible, setOutVisible] = useState<boolean>(false);
  const [componentVisibleText, setComponentVisibleText] = useReducer(
    (state: JSX.Element | string, action: string) => {
      switch (action) {
        case 'list':
          setPageName('优惠券列表');
          return '';
        case 'add':
          setPageName('添加优惠券');
          return ElementComponent.AddElement;
      }
      return state;
    },
    '',
  );

  const AddClose = () => {
    setComponentVisibleText('list');
  };
  const columns: ProColumns<orderList>[] = [
    {
      title: '券id',
      dataIndex: 'id',
      hideInForm: true,
    },
    {
      title: '批次码',
      dataIndex: 'code',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '优惠券名称',
      dataIndex: 'title',
      hideInSearch: true,
    },
    {
      title: '优惠券子标题',
      dataIndex: 'subTitle',
      hideInSearch: true,
    },
    {
      title: '优惠券数量',
      dataIndex: 'count',
      hideInSearch: true,
    },
    {
      title: '每人限领数量',
      dataIndex: 'userLimitCount',
      hideInSearch: true,
    },
    {
      title: '每日限领数量',
      dataIndex: 'dayLimitCount',
      hideInSearch: true,
    },
    {
      title: '有效期开始',
      dataIndex: 'startDate',
      hideInSearch: true,
      renderFormItem: () => {
        return (
          <DatePicker.RangePicker
            showTime
            placeholder={['请选择时间', '请选择时间']}
            disabledDate={disabledDate}
          />
        );
      },
    },
    {
      title: '有效期结束',
      dataIndex: 'endDate',
      hideInSearch: true,
      renderFormItem: () => {
        return (
          <DatePicker.RangePicker
            showTime
            placeholder={['请选择时间', '请选择时间']}
            disabledDate={disabledDate}
          />
        );
      },
    },
    {
      fixed: 'right',
      title: '操作',
      hideInSearch: true,
      render: (_, record) => {
        return (
          <>
            <a
              onClick={() => {
                setOutVisible(true);
                setDetailId(record.id);
              }}
            >
              发放
            </a>
            <Divider type="vertical" />
            <a
              onClick={() => {
                setDetailId(record.id);
                setPassVisible(true);
              }}
            >
              数据统计
            </a>
            <Divider type="vertical" />
            {record.is_deletable && (
              <a
                onClick={() => {
                  Modal.confirm({
                    title: `确定要删除${record.id}优惠券吗，?`,
                    icon: <ExclamationCircleFilled />,
                    content: '注意此操作不可逆',
                    okType: 'default',
                    centered: true,
                    async onOk() {
                      const res = await deleteTemplate(record.id);
                      if (res) {
                        message.success('删除成功');
                        actionRef.current?.reload();
                      }
                    },
                  });
                }}
              >
                删除
              </a>
            )}
          </>
        );
      },
    },
  ];
  return (
    <PageContainer
      title={
        <div>
          {componentVisibleText && (
            <Button
              // disabled={returnPlay}
              type="link"
              onClick={() => {
                setComponentVisibleText('list');
              }}
            >
              <img
                className={styles.toolBarImg}
                src={'/icons/arrow-return-left.svg'}
                alt="Picture of the author"
                width="21"
                height="21"
              />
            </Button>
          )}
          {pageName}
        </div>
      }
    >
      {!componentVisibleText && (
        <ProTable<any>
          actionRef={actionRef}
          rowKey="parkingOrderId"
          columns={columns}
          scroll={{ x: true }}
          style={{ whiteSpace: 'nowrap' }}
          columnEmptyText="-"
          headerTitle="订单列表"
          pagination={{
            size: 'default',
            showQuickJumper: true,
            showSizeChanger: true,
            defaultPageSize: 10,
          }}
          toolBarRender={() => [
            <Button
              key="button"
              icon={<PlusOutlined />}
              type="primary"
              onClick={async () => {
                setComponentVisibleText('add');
              }}
            >
              添加
            </Button>,
          ]}
          request={async (param) => {
            const res: any = await getOrderTable(param);
            return { ...res, data: res.data.list, success: true, total: res.data.total };
          }}
        />
      )}
      {componentVisibleText}
      <ModalForm
        layout="vertical"
        width={450}
        // labelCol={{ span: 50 }}
        // wrapperCol={{ span: 14 }}
        onFinish={async (values) => {
          const res = await couponTemplateItem({
            templateId: detailId,
            phones: values.phone.map((obj: { value: any }) => obj.value),
          });
          if (res && res.code == 0) {
            setOutVisible(false);
            message.success('优惠券投放成功');
            actionRef.current?.reload();
            return true;
          } else {
            message.error('优惠券投放失败' + res?.message);
            return false;
          }
        }}
        visible={outVisible}
        title="优惠券投放"
        formRef={formRef}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            setOutVisible(false);
          },
          centered: true,
          footer: null,
        }}
      >
        <ProFormList
          name="phone"
          min={1}
          initialValue={[
            {
              value: '',
            },
          ]}
          copyIconProps={false}
          deleteIconProps={{
            Icon: CloseCircleOutlined,
            tooltipText: '不需要这行了',
          }}
        >
          <ProFormText
            name="value"
            label="批量输入手机号"
            placeholder="请输入手机号"
            rules={[
              { required: true, message: '手机号不能为空' },
              { len: 11, message: '手机号必须为11个字符' },
            ]}
          />
        </ProFormList>
      </ModalForm>
      {passVisible && (
        <Detail
          visible={passVisible}
          onClose={() => {
            setPassVisible(false);
          }}
          id={detailId}
        />
      )}
    </PageContainer>
  );
};
